<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Dish;
use App\Traits\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class CategoryController extends Controller
{
    use ApiResponse;

    /**
     * 获取分类列表（简化版，无层级结构）
     */
    public function tree(): JsonResponse
    {
        try {
            $categories = Category::active()
                ->ordered()
                ->get(['id', 'name', 'slug', 'description', 'dish_count']);

            return $this->success([
                'categories' => $categories,
            ], '获取分类列表成功');

        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    /**
     * 获取分类列表（与tree方法相同，保持兼容性）
     */
    public function main(): JsonResponse
    {
        try {
            $categories = Category::active()
                ->ordered()
                ->get(['id', 'name', 'slug', 'description', 'dish_count']);

            return $this->success([
                'categories' => $categories,
            ], '获取分类列表成功');

        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    /**
     * 获取子分类列表（暂时禁用，因为当前迁移文件不支持层级结构）
     */
    public function sub(Request $request): JsonResponse
    {
        return $this->error('子分类功能暂时不可用，当前版本不支持层级分类', 50001);
    }

    /**
     * 获取分类详情
     */
    public function show(Category $category): JsonResponse
    {
        try {
            if (!$category->is_active) {
                throw new \App\Exceptions\BusinessException('分类不存在', 20005);
            }

            return $this->success([
                'category' => [
                    'id' => $category->id,
                    'name' => $category->name,
                    'slug' => $category->slug,
                    'description' => $category->description,
                    'dish_count' => $category->dish_count,
                    'sort_order' => $category->sort_order,
                    'is_active' => $category->is_active,
                ],
            ], '获取分类详情成功');

        } catch (\Exception $e) {
            return $this->error('获取分类详情失败：' . $e->getMessage(), 50001);
        }
    }

    /**
     * 获取分类下的菜品
     */
    public function dishes(Request $request, Category $category): JsonResponse
    {
        try {
            if (!$category->is_active) {
                throw new \App\Exceptions\BusinessException('分类不存在', 20005);
            }

            $request->validate([
                'limit' => 'sometimes|integer|min:1|max:100',
                'offset' => 'sometimes|integer|min:0',
                'featured' => 'sometimes|boolean',
            ]);

            $limit = $request->input('limit', 20);
            $offset = $request->input('offset', 0);

            $query = $category->dishes()->available();

            // 是否只显示推荐菜品
            if ($request->boolean('featured')) {
                $query->featured();
            }

            $dishes = $query->with('category')
                ->orderBy('sort_order')
                ->orderBy('name')
                ->offset($offset)
                ->limit($limit)
                ->get();

            $total = $category->dishes()->available()->count();

            return $this->success([
                'dishes' => $dishes,
                'pagination' => [
                    'total' => $total,
                    'limit' => $limit,
                    'offset' => $offset,
                    'has_more' => $offset + $limit < $total,
                ],
            ], '获取分类菜品成功');

        } catch (\Exception $e) {
            return $this->error('获取分类菜品失败：' . $e->getMessage(), 50001);
        }
    }

    /**
     * 搜索分类
     */
    public function search(Request $request): JsonResponse
    {
        try {
            $request->validate([
                'keyword' => 'required|string|min:1|max:255',
            ]);

            $keyword = $request->input('keyword');

            $query = Category::active()
                ->where(function ($q) use ($keyword) {
                    $q->where('name', 'like', "%{$keyword}%")
                      ->orWhere('slug', 'like', "%{$keyword}%")
                      ->orWhere('description', 'like', "%{$keyword}%");
                });

            $categories = $query->ordered()
                ->limit(20)
                ->get();

            return $this->success([
                'categories' => $categories,
                'total' => $categories->count(),
            ], '搜索分类成功');

        } catch (\Exception $e) {
            return $this->error('搜索分类失败：' . $e->getMessage(), 50001);
        }
    }

    /**
     * 获取分类统计信息
     */
    public function stats(): JsonResponse
    {
        try {
            $stats = [
                'total_categories' => Category::active()->count(),
                'total_dishes' => Dish::available()->count(),
                'categories_with_dishes' => Category::active()->where('dish_count', '>', 0)->count(),
            ];

            return $this->success([
                'stats' => $stats,
            ], '获取分类统计成功');

        } catch (\Exception $e) {
            return $this->error('获取分类统计失败：' . $e->getMessage(), 50001);
        }
    }
}